/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.consumer.cluster.impl;

import com.alibaba.fastjson.JSON;
import com.lvyh.lightframe.common.constant.RpcConstants;
import com.lvyh.lightframe.core.invoke.RpcInternalContext;
import com.lvyh.lightframe.core.provider.ProviderHelper;
import com.lvyh.lightframe.core.provider.ProviderInfo;
import com.lvyh.lightframe.core.consumer.cluster.AbstractCluster;
import com.lvyh.lightframe.core.consumer.route.LoadBalance;
import com.lvyh.lightframe.core.consumer.transport.AbstractClient;
import com.lvyh.lightframe.common.ext.ExtensionLoaderFactory;
import com.lvyh.lightframe.common.ext.Spi;
import com.lvyh.lightframe.core.invoke.request.RpcRequest;
import com.lvyh.lightframe.core.invoke.response.RpcResponse;
import com.lvyh.lightframe.common.exception.RpcRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * If the server fails, it will switch automatically. When the server fails,
 * it will try again to other servers (the default).
 * It is usually used for read operation, but the retrial will bring longer delay.
 * You can set the number of retries (excluding the first one) by means of retries = 2
 */
@Spi("failover")
public class FailoverCluster extends AbstractCluster {
    private Logger logger = LoggerFactory.getLogger(FailoverCluster.class);

    public FailoverCluster(LoadBalance loadBalance) {
        super(loadBalance);
    }

    @Override
    public RpcResponse doInvoke(RpcRequest request) throws RpcRuntimeException {
        String methodName = request.getMethodName();
        int retries = 2;
        int time = 0;
        RpcRuntimeException throwable = null;
        List<ProviderInfo> invokedProviderInfos = new ArrayList<ProviderInfo>(retries + 1);
        do {
            ProviderInfo providerInfo = select(request, loadBalance);
            request.setServerAddress(ProviderHelper.convert(providerInfo));
            try {
                AbstractClient client = ExtensionLoaderFactory.getExtensionLoader(AbstractClient.class).getExtension(request.getTransport());
                RpcResponse response = doInvoke(client, request);
                logger.info("[FailoverCluster] consumer cluster execute invoke romote service,time:{}, request:{}, response:{}", time, JSON.toJSONString(request), JSON.toJSONString(response));

                if (response != null) {
                    if (throwable != null) {
                        logger.error("[FailoverCluster] consumer cluster execute invoke error,time:{}, className:{}, message:{},provider:{}", time, throwable.getClass(), throwable.getMessage(), invokedProviderInfos);
                    }
                    return response;
                } else {
                    throwable = new RpcRuntimeException("Failed to call " + request.getClassName() + "." + methodName + " on remote server " + providerInfo + ", return null");
                    time++;
                }
            } catch (RpcRuntimeException e) {
                logger.error("[FailoverCluster] consumer doInvoke error,time:{}, message:{},provider:{}", time, e, invokedProviderInfos);
                throwable = e;
                time++;
            } catch (Exception e) { // Do not try again for other exceptions
                throw new RpcRuntimeException("Failed to call " + request.getClassName() + "." + request.getMethodName()
                        + " on remote server: " + providerInfo + ", cause by unknown exception: "
                        + e.getClass().getName() + ", message is: " + e.getMessage(), e);
            } finally {
                RpcInternalContext.getContext().setAttachment(RpcConstants.INTERNAL_KEY_INVOKE_TIMES, time + 1); // retry count
            }
            invokedProviderInfos.add(providerInfo);
        } while (time <= retries);

        throw throwable;
    }

}
